<template>
  <view class="content-comment flex flex-between p-a-ll align-center">
    <up-icon
      name="camera"
      color="#2979ff"
      size="28"
      @click="choseImg"
    ></up-icon>
    <editor
      id="editor-com"
      show-img-size
      show-img-toolbar
      show-img-resize
      class="editor-com font-12"
      :placeholder="placeholder"
      @ready="onEditorReady"
    >
    </editor>
    <view class="flex relative">
      <view class="biaoqing-icon" @click="show = true">
        <up-icon name="weixin-fill" size="20"></up-icon>
      </view>
      <view class="m-l-l">
        <up-button @click="commont" type="primary" size="mini">发送</up-button>
      </view>
    </view>
  </view>
  <up-popup :show="show">
    <emoVue @swiperChange="handleEmojiChange"></emoVue>
  </up-popup>
</template>

<script setup>
defineOptions({
  options: { styleIsolation: "shared" },
});
import { getCurrentInstance, onMounted, ref } from "vue";
import emoVue from "./emo.vue";
import { addComment, uploadFile } from "../utils/api";
import { dbGet } from "../utils/db";

const props = defineProps({
  nowComment: {
    type: Object,
    default: () => {
      return {};
    },
  },
  type: {
    type: String,
    //还有一种是message
    default: "comment",
  },
  nowMessageId: {
    default: "",
  },
});
const emit = defineEmits(["success"]);
let editorCtx = null;
const instace = getCurrentInstance();
const onEditorReady = () => {
  uni
    .createSelectorQuery()
    .in(instace.proxy)
    .select("#editor-com")
    .context((res) => {
      editorCtx = res.context;
    })
    .exec();
};
const placeholder = ref("");
const show = ref(false);
const handleEmojiChange = (src) => {
  editorCtx.insertImage({
    src,
    width: "20",
    height: "20",
    nowrap: true,
  });
  show.value = false;
};
const commont = () => {
  editorCtx.getContents({
    success: ({ html }) => {
      debugger;
      if (props.type === "comment") {
        let { sub_index, discuss_index, id, sub_openid } = props.nowComment;
        let params = {
          discuss_index,
          content: html,
          id,
        };
        if (sub_index !== undefined) {
          params["sub_index"] = sub_index;
          params["sub_openid"] = sub_openid;
        }
        addComment(params)
          .then((res) => {
            if (res.code === 200) {
              uni.showToast({
                title: "新增成功",
              });
              editorCtx.clear();
              placeholder.value = "";
              emit("success");
            }
          })
          .catch(() => {});
      } else {
        //发送消息
        let msg = {
          openid: dbGet("openid"),
          id: props.nowMessageId,
          message: html,
        };
        uni.sendSocketMessage({
          data: JSON.stringify(msg),
          success: (res) => {
            editorCtx.clear();
            emit("success", html);
          },
          fail(err) {},
        });
      }
    },
  });
};
const choseImg = () => {
  uni.chooseImage({
    count: 1, // 默认9，设置图片的数量
    sizeType: ["original", "compressed"], // 可以指定是原图还是压缩图，默认二者都有
    sourceType: ["album", "camera"], // 可以指定来源是相册还是相机，默认二者都有
    success: (chooseImageRes) => {
      const tempFilePaths = chooseImageRes.tempFilePaths;
      uploadFile({
        url: tempFilePaths[0],
      }).then((res) => {
        let url = res.data.url;
        let html = `<img src="${url}" width=200  height=150/>`;
        let { id, discuss_index } = props.nowComment;
        addComment({ id, discuss_index, content: html })
          .then((res) => {
            if (res.code === 200) {
              emit("success");
            }
          })
          .catch(() => {});
      });
    },
    fail: (chooseImageErr) => {
      console.error("选择图片失败", chooseImageErr);
    },
  });
};
const setPlaceholder = (text) => {
  placeholder.value = text;
  editorCtx.setContents({
    html: "",
  });
};
defineExpose({
  setPlaceholder,
});
</script>

<style lang="less" scoped>
.content-comment {
  box-sizing: border-box;
  // background: white;
  // position: fixed;
  // bottom: 0;
  width: 100%;
}

.editor-com {
  flex: 1;
  position: relative;
  // width: 60%;
  padding: 10upx;
  padding-right: 50upx;
  box-sizing: border-box;
  background: rgb(246, 245, 245) !important;
  min-height: 40upx !important;
  height: auto !important;
  border-radius: 10px;
}

.biaoqing-icon {
  position: absolute;
  left: -50upx;
  bottom: 0;
}

/deep/.u-button {
  height: 50upx;
}

.my-bt {
  width: 160upx;
  height: 60upx !important;
}
</style>
